﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using SarkothFarmer.Helpers;
using Zeta;
using Zeta.Common;

namespace SarkothFarmer.Settings
{
    public class SettingsWrapper
    {
        private Dictionary<string, object> settingValues;
        private Dictionary<string, object> globalSettingValues;
        [BrowsableAttribute(false)]
        public Dictionary<string, object> GlobalSettingValues
        {
            get { return globalSettingValues; }
        }
        [BrowsableAttribute(false)]
        public Dictionary<string, object> SettingValues
        {
            get { return settingValues; }
        }
        // Constructor
        public SettingsWrapper()
        {
            LoadSettings();
        }

        public enum TrueFalseDefault
        {
            Default = 0,
            True = 1,
            False = 2,
        }

        public const string pickupGold = "Pickup Gold";
        [Description("Pickup gold in stacks with at least this much gold.")]
        public int PickupGold
        {
            get { return (int)settingValues[pickupGold]; }
            set { settingValues[pickupGold] = value; }
        }

        public const string safeTPDistance = "Safe TP Distance";
        [Description("Use an ability for safe TP if there are mobs within this range.")]
        public int SafeTPDistance
        {
            get { return (int)settingValues[safeTPDistance]; }
            set { settingValues[safeTPDistance] = value; }
        }

        public const string maxTime = "Max Time";
        [Description("Will leave game after this amount of seconds has passed.")]
        public int MaxTime
        {
            get { return (int)settingValues[maxTime]; }
            set { settingValues[maxTime] = value; }
        }

        public const string fastCellar = "Fast Cellar";
        [Description("Should it use 'fast-move' inside the cellar aswell?\nNOTE: This has no effect for Demon Hunters")]
        public TrueFalseDefault FastCellar
        {
            get { return (TrueFalseDefault)settingValues[fastCellar]; }
            set { settingValues[fastCellar] = (int)value; }
        }

        public const string update = "Update";
        [Description("Should you be prompted with new updates?")]
        public bool Update
        {
            get { return (bool)globalSettingValues[update]; }
            set { globalSettingValues[update] = value; }
        }

        public const string currentRev = "Current Rev";
        [ReadOnlyAttribute(true)]
        public int CurrentRev
        {
            get { return (int)globalSettingValues[currentRev]; }
            set { globalSettingValues[currentRev] = value; }
        }

        private Dictionary<string, object> DefaultValues
        {
            get
            {
                var settings = new Dictionary<string, object>
                                   {
                                       {pickupGold, 500},
                                       {safeTPDistance, 35},
                                       {maxTime, 40},
                                       {fastCellar, 0},
                                   };
                return settings;
            }
        }
        private Dictionary<string, object> DefaultGlobalValues
        {
            get
            {
                var settings = new Dictionary<string, object>
                                   {
                                       {update, true},
                                       {currentRev, 30},
                                   };
                return settings;
            }
        }

        private static string SettingsPath
        {
            get
            {
                return Path.Combine(Environment.CurrentDirectory, "Settings", ZetaDia.Service.CurrentHero.BattleTagName,
                                    "SarkothFarmer.xml");
            }
        }

        private static string GlobalSettingsPath
        {
            get
            {
                return Path.Combine(Environment.CurrentDirectory, "Settings", "SarkothFarmer.xml");
            }
        }

        public void LoadSettings()
        {
            settingValues = GetSettingsFromFile(SettingsPath, DefaultValues, true);
            globalSettingValues = GetSettingsFromFile(GlobalSettingsPath, DefaultGlobalValues, false);
        }
        public Dictionary<string, object> GetSettingsFromFile(string path, Dictionary<string, object> defaults, bool checkExist)
        {
            if (File.Exists(path))
            {
                using (XmlReader reader = XmlReader.Create(path))
                {
                    try
                    {
                        var serializer = new DataContractSerializer(typeof(Dictionary<string, object>));
                        var temp = (Dictionary<string, object>)serializer.ReadObject(reader);
                        if (temp != null)
                        {
                            foreach (var o in temp)
                            {
                                defaults[o.Key] = o.Value;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Logging.WriteException(ex);
                        Logger.WriteDiagnostic("No settings file found! Using default values.");
                        throw;
                    }
                }
            }
            else if (checkExist)
            {
                MessageBox.Show(
                "It looks like you haven't configured SarkothFarmer yet. Please do so by clicking the plugin in the plugins tab.",
                "SarkothFarmer config");
            }
            return defaults;
        }

        public void SaveSettings()
        {
            var settingsWriter = new XmlWriterSettings { Indent = true };
            using (XmlWriter writer = XmlWriter.Create(SettingsPath, settingsWriter))
            {
                var serializer = new DataContractSerializer(typeof(Dictionary<string, object>));
                serializer.WriteObject(writer, settingValues);
            }
        }
        public void SaveGlobalSettings()
        { 
            var settingsWriter = new XmlWriterSettings { Indent = true };
            using (XmlWriter writer = XmlWriter.Create(GlobalSettingsPath, settingsWriter))
            {
                var serializer = new DataContractSerializer(typeof(Dictionary<string, object>));
                serializer.WriteObject(writer, globalSettingValues);
            }
        }
    }

}
